import 'package:flutter/material.dart';
import 'package:flutter_app/models/FuLi.dart';
import 'package:dio/dio.dart';
import 'package:flutter_app/models/Girl.dart';
import 'package:flutter_app/Toast.dart';

class GirlImages extends StatefulWidget {
  @override
  _GirlImagesState createState() {
    return _GirlImagesState();
  }
}

class _GirlImagesState extends State<GirlImages> {
  List<Girl> _girls;
  PageController _controller = new PageController();
  int pageSize = 1;

  @override
  void initState() {
    // TODO: implement initState
    _controller.addListener(() {
      print(_controller.page);
      if (_girls != null &&
          _girls.isNotEmpty &&
          _controller.page == _girls.length - 1) {
        pageSize++;
        getFuli();
        Toast.toast(context, "加载更多。。。");
      }
    });
    getFuli();
  }

  void getFuli() async {
    try {
      Dio dio = new Dio();
      Options options = new Options(
          baseUrl: "http://gank.io/api/data/福利",
          connectTimeout: 5000,
          receiveTimeout: 5000);
      dio.options = options;
      Future future = dio.get("/10/$pageSize");
      future.then((data) {
        print(data);
        FuLi fuLi = new FuLi.fromJson(data.data);
//        _girls = fuLi.results;
        setState(() {
          if (pageSize == 1) {
            _girls = fuLi.results;
          } else {
            _girls.addAll(fuLi.results);
          }
        });
        print(fuLi.results);
      }).catchError((error) {
        print(error);
      });
    } catch (e) {
      return print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      child: PageView.builder(
        itemBuilder: (context, index) {
          return GestureDetector(
            child: Image.network(
                _girls != null && _girls.isNotEmpty ? _girls[index].url : ""),
            onTap: () {
              Toast.toast(context, "时间：${_girls[index].desc}");
            },
          );
        },
        itemCount: _girls != null && _girls.isNotEmpty ? _girls.length : 0,
        controller: _controller,
      ),
    );
  }
}
